<template>
  <view class="intention-page">
    <nav-header title="求职意向"></nav-header>
    
    <view class="content" :style="{ marginTop: statusBarHeight + 44 + 'px' }">
      <view class="page-title">求职意向</view>
      <view class="subtitle">填写你的期望工作信息</view>
      
      <view class="form-container">
        <!-- Job Position -->
        <view class="form-item">
          <text class="label">期望职位 <text class="required">*</text></text>
          <view class="input-wrapper position-relative">
            <input type="text" v-model="intention.jobPosition" placeholder="请输入期望职位" @input="handleJobPositionInput" @focus="handleJobPositionFocus" @blur="handleJobPositionBlur" />
            <!-- 职位下拉建议框 -->
            <view class="dropdown-suggestions" v-if="showJobPositionDropdown && filteredJobPositions.length > 0">
              <view 
                class="suggestion-item" 
                v-for="(position, index) in filteredJobPositions" 
                :key="index"
                @click="selectJobPosition(position)"
              >
                {{ position }}
              </view>
            </view>
          </view>
          <!-- <view class="input-wrapper" @click="showPositionPicker = true">
            <text class="input-text" :class="{ placeholder: !intention.jobPosition }">
              {{ intention.jobPosition || '请选择期望职位' }}
            </text>
            <text class="arrow">›</text>
          </view> -->
        </view>
        
        <!-- Job Category -->
        <view class="form-item">
          <text class="label">职位类别 <text class="required">*</text></text>
          <view class="input-wrapper" @click="showCategoryPicker = true">
            <text class="input-text" :class="{ placeholder: !intention.jobType }">
              {{ intention.jobType || '请选择职位类别' }}
            </text>
            <text class="arrow">›</text>
          </view>
        </view>
        
        <!-- Expected Salary -->
        <view class="form-item">
          <text class="label">期望薪资</text>
          <view class="salary-input">
            <view class="input-wrapper" @click="showSalaryPicker = true">
              <text class="input-text" :class="{ placeholder: !intention.expectedSalary }">
                {{ intention.expectedSalary || '请选择期望薪资范围' }}
              </text>
              <text class="arrow">›</text>
            </view>
          </view>
        </view>
        
        <!-- Job Location -->
        <view class="form-item">
          <text class="label">意向城市 <text class="required">*</text></text>
          <view class="input-wrapper">
            <input type="text" v-model="intention.intendedCity" placeholder="请输入期望地点" />
          </view>
          <!-- <view class="location-wrapper">
            <view 
              v-for="(location, index) in intention.locations" 
              :key="index"
              class="location-tag"
            >
              <text>{{ location }}</text>
              <text class="remove-icon" @click="removeLocation(index)">×</text>
            </view>
            
            <view 
              class="location-tag add-location" 
              @click="showLocationPicker = true"
              v-if="intention.locations.length < 3"
            >
              <text class="add-icon">+</text>
              <text>添加地点</text>
            </view>
          </view> -->
        </view>
        
        <!-- Job Type -->
<!--        <view class="form-item">
          <text class="label">工作类型</text>
          <view class="job-type-options">
            <view 
              v-for="type in jobTypes" 
              :key="type.value"
			  class="job-type-option"
              :class=" {active: intention.jobType === type.value }"
              @click="intention.jobType = type.value">
              <text>{{ type.label }}</text>
            </view>
          </view>
        </view> -->
      </view>
    </view>
      
    <!-- Save Button -->
    <view class="action-bar">
      <button class="save-btn" @click="saveIntention">保存</button>
    </view>
    
    <!-- Position Picker Popup -->
    <uni-popup ref="positionPopup" type="bottom" @change="handlePositionPopupChange">
      <view class="picker-popup">
        <view class="picker-header">
          <text class="cancel-btn" @click="showPositionPicker = false">取消</text>
          <text class="title">选择期望职位</text>
          <text class="confirm-btn" @click="confirmPosition">确定</text>
        </view>
        <picker-view 
          class="picker-view" 
          :value="positionIndexes" 
          @change="handlePositionChange"
        >
          <picker-view-column>
            <view class="picker-item" v-for="item in positions" :key="item">{{ item }}</view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>
    
    <!-- Category Picker Popup -->
    <uni-popup ref="categoryPopup" type="bottom" @change="handleCategoryPopupChange">
      <view class="picker-popup">
        <view class="picker-header">
          <text class="cancel-btn" @click="showCategoryPicker = false">取消</text>
          <text class="title">选择职位类别</text>
          <text class="confirm-btn" @click="confirmCategory">确定</text>
        </view>
        <picker-view 
          class="picker-view" 
          :value="categoryIndexes" 
          @change="handleCategoryChange"
        >
          <picker-view-column>
            <view class="picker-item" v-for="item in jobTypes" :key="item">{{ item }}</view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>
    
    <!-- Salary Picker Popup -->
    <uni-popup ref="salaryPopup" type="bottom" @change="handleSalaryPopupChange">
      <view class="picker-popup">
        <view class="picker-header">
          <text class="cancel-btn" @click="showSalaryPicker = false">取消</text>
          <text class="title">选择期望薪资</text>
          <text class="confirm-btn" @click="confirmSalary">确定</text>
        </view>
        <picker-view 
          class="picker-view" 
          :value="salaryIndexes" 
          @change="handleSalaryChange"
        >
          <picker-view-column>
            <view class="picker-item" v-for="item in salaryMain" :key="item">{{ item }}</view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>
    
    <!-- Location Picker Popup -->
    <uni-popup ref="locationPopup" type="bottom" @change="handleLocationPopupChange">
      <view class="picker-popup">
        <view class="picker-header">
          <text class="cancel-btn" @click="showLocationPicker = false">取消</text>
          <text class="title">选择期望地点</text>
          <text class="confirm-btn" @click="confirmLocation">确定</text>
        </view>
        <picker-view 
          class="picker-view" 
          :value="locationIndexes" 
          @change="handleLocationChange"
        >
          <picker-view-column>
            <view class="picker-item" v-for="item in provinces" :key="item">{{ item }}</view>
          </picker-view-column>
          <picker-view-column>
            <view class="picker-item" v-for="item in cities" :key="item">{{ item }}</view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import NavHeader from '@/components/nav-header.vue'
import { onLoad } from '@dcloudio/uni-app'
import {
  getJobIntentionDetail,
  addJobIntention,
  updateJobIntention,
  deleteJobIntention,
  getJobIntentionList
} from '@/api/edit/intention'
import {
		useResumeStore
	} from '@/store/resume.js'

const statusBarHeight = ref(20)
const positionPopup = ref(null)
const showPositionPicker = ref(false)
const positionIndexes = ref([0])
const positions = [
  '前端开发工程师', '后端开发工程师', '全栈工程师', 
  'iOS开发工程师', 'Android开发工程师', '小程序开发工程师',
  '算法工程师', '数据分析师', '产品经理', 
  'UI设计师', 'UX设计师', '运营专员',
  '市场营销', '人力资源', '财务专员'
]
const categoryPopup = ref(null)
const showCategoryPicker = ref(false)
const categoryIndexes = ref([0])
const categories = [
  '互联网/IT/通信', '金融/银行/保险', '贸易/消费/制造',
  '教育/培训', '医疗/健康', '服务业',
  '房地产/建筑', '广告/传媒/文化', '能源/环保'
]
const salaryPopup = ref(null)
const showSalaryPicker = ref(false)
const salaryIndexes = ref([0, 0, 0])
const salaryMain = ['面议', '2K-4K','4K-6K','6K-8K','8K-10K','10K-12K','12K-15K','15K-20K','20K-30K','30K-50K','50K-100K','100K-200K','200K-500K','500K-1000K']
const locationPopup = ref(null)
const showLocationPicker = ref(false)
const locationIndexes = ref([0, 0])
const provinces = ['北京', '上海', '广东', '江苏', '浙江', '四川', '湖北', '山东', '河南', '福建']
const citiesMap = {
  '北京': ['全市'],
  '上海': ['全市'],
  '广东': ['广州', '深圳', '珠海', '汕头', '佛山', '东莞'],
  '江苏': ['南京', '苏州', '无锡', '常州', '南通', '扬州'],
  '浙江': ['杭州', '宁波', '温州', '嘉兴', '湖州', '绍兴'],
  '四川': ['成都', '绵阳', '德阳', '南充', '宜宾', '乐山'],
  '湖北': ['武汉', '宜昌', '襄阳', '荆州', '十堰', '黄石'],
  '山东': ['济南', '青岛', '烟台', '潍坊', '临沂', '济宁'],
  '河南': ['郑州', '洛阳', '开封', '南阳', '新乡', '许昌'],
  '福建': ['福州', '厦门', '泉州', '漳州', '三明', '莆田']
}
const cities = computed(() => {
  return citiesMap[provinces[locationIndexes.value[0]]] || []
})
const isAdding = ref(true)
const currentId = ref(null)
const intention = reactive({
  jobPosition: '',
  jobType: '',
  intendedCity: '',
  expectedSalary: ''
})
const jobTypes = ['全职', '兼职', '实习','自由职业']
const resumeStore = useResumeStore()

// 职位建议列表
const jobPositionSuggestions = ref([])
const showJobPositionDropdown = ref(false)
const isInputFocused = ref(false)

onLoad(async (options) => {
  if (options.index) {
    isAdding.value = false
    currentId.value = options.index
    await fetchIntentionDetail(options.index)
  } else {
    isAdding.value = true
    resetForm()
  }
})

onMounted(() => {
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight
  
  // 获取职位建议列表
  fetchJobPositionSuggestions()
})

function resetForm() {
  intention.jobPosition = ''
  intention.jobType = ''
  intention.intendedCity = ''
  intention.expectedSalary = ''
}

async function fetchIntentionDetail(id) {
  try {
    uni.showLoading({ title: '加载中...' })
    const res = await getJobIntentionDetail(id)
    if (res.code === 200 && res.data) {
      Object.assign(intention, res.data)
      if (intention.jobType) {
        const index = jobTypes.findIndex(item => item === intention.jobType)
        if (index !== -1) categoryIndexes.value = [index]
      }
    }
  } catch (e) {
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

watch(showPositionPicker, (val) => {
  if (val) positionPopup.value.open()
  else positionPopup.value.close()
})
watch(showCategoryPicker, (val) => {
  if (val) categoryPopup.value.open()
  else categoryPopup.value.close()
})
watch(showSalaryPicker, (val) => {
  if (val) salaryPopup.value.open()
  else salaryPopup.value.close()
})
watch(showLocationPicker, (val) => {
  if (val) locationPopup.value.open()
  else locationPopup.value.close()
})
const handlePositionPopupChange = (e) => {
  if (!e.show) showPositionPicker.value = false
}
const handlePositionChange = (e) => {
  positionIndexes.value = e.detail.value
}
const confirmPosition = () => {
  intention.position = positions[positionIndexes.value[0]]
  showPositionPicker.value = false
}
const handleCategoryPopupChange = (e) => {
  if (!e.show) showCategoryPicker.value = false
}
const handleCategoryChange = (e) => {
  categoryIndexes.value = e.detail.value
}
const confirmCategory = () => {
  intention.jobType = jobTypes[categoryIndexes.value[0]]
  showCategoryPicker.value = false
}
const handleSalaryPopupChange = (e) => {  
  if (!e.show) showSalaryPicker.value = false
}
const handleSalaryChange = (e) => {
  salaryIndexes.value = e.detail.value
}
const confirmSalary = () => {
  intention.expectedSalary = salaryMain[salaryIndexes.value[0]]
  showSalaryPicker.value = false
}
const handleLocationPopupChange = (e) => {
  if (!e.show) showLocationPicker.value = false
}
const handleLocationChange = (e) => {
  const [provinceIndex, cityIndex] = e.detail.value
  if (provinceIndex !== locationIndexes.value[0]) {
    locationIndexes.value = [provinceIndex, 0]
  } else {
    locationIndexes.value = e.detail.value
  }
}
const confirmLocation = () => {
  const province = provinces[locationIndexes.value[0]]
  const city = cities.value[locationIndexes.value[1]]
  const intendedCity = province === '北京' || province === '上海' ? province : `${province}-${city}`
  if (!intention.intendedCity.includes(intendedCity)) {
    intention.intendedCity.push(intendedCity)
  }
  showLocationPicker.value = false
}
const removeLocation = (index) => {
  intention.intendedCity.splice(index, 1)
}
const saveIntention = async () => {
  if (!intention.jobPosition) { uni.showToast({ title: '请选择期望职位', icon: 'none' }); return }
  if (!intention.jobType) { uni.showToast({ title: '请选择职位类别', icon: 'none' }); return }
  if (!intention.intendedCity) { uni.showToast({ title: '请至少添加一个期望地点', icon: 'none' }); return }
  try {
    uni.showLoading({ title: '保存中...' })
    let res
    const params = { 
      ...intention,
      // resumeId: '1916784587136589826',
      resumeId:resumeStore.resumeId,
     }
    if (isAdding.value) {
      res = await addJobIntention(params)
    } else {
      params.id = currentId.value
      res = await updateJobIntention(params)
    }
    if (res.code === 200) {
      uni.showToast({ title: '保存成功', icon: 'success' })
      setTimeout(() => { uni.navigateBack() }, 1500)
    } else {
      uni.showToast({ title: res.msg || '保存失败', icon: 'none' })
    }
  } catch (e) {
    uni.showToast({ title: '保存失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

// 获取职位建议列表
async function fetchJobPositionSuggestions() {
  try {
    const res = await getJobIntentionList()
    if (res.code === 200 && res.rows) {
      // 提取不重复的职位名称
      const positions = new Set()
      res.rows.forEach(item => {
        if (item.jobPosition) {
          positions.add(item.jobPosition)
        }
      })
      jobPositionSuggestions.value = Array.from(positions)
      console.log(jobPositionSuggestions.value)
    }
  } catch (error) {
    console.error('获取职位建议失败', error)
  }
}

// 处理职位输入
function handleJobPositionInput(e) {
  intention.jobPosition = e.detail.value
  
  if (isInputFocused.value) {
    showJobPositionDropdown.value = true  // 保持下拉框显示
  }
}

// 处理职位输入框获取焦点
function handleJobPositionFocus() {
  isInputFocused.value = true
  showJobPositionDropdown.value = true  // 无条件显示下拉框
}

// 处理职位输入框失去焦点
function handleJobPositionBlur() {
  // 延迟关闭下拉框，以便可以点击下拉选项
  setTimeout(() => {
    isInputFocused.value = false
    showJobPositionDropdown.value = false
  }, 200)
}

// 选择职位建议
function selectJobPosition(position) {
  intention.jobPosition = position
  showJobPositionDropdown.value = false
}

// 获取筛选后的职位建议
const filteredJobPositions = computed(() => {
  if (!intention.jobPosition) return jobPositionSuggestions.value  // 空输入时返回全部建议
  
  return jobPositionSuggestions.value.filter(position => 
    position.toLowerCase().includes(intention.jobPosition.toLowerCase())
  )
})
</script>

<style lang="scss" scoped>
.intention-page {
  min-height: 100vh;
  background-color: #FFFFFF;
  padding-bottom: 70px;
  
  .content {
    padding: 20px;
    
    .page-title {
      font-size: 24px;
      font-weight: bold;
      color: #333;
      margin-bottom: 6px;
    }
    
    .subtitle {
      font-size: 14px;
      color: #999;
      margin-bottom: 24px;
    }
  }
  
  .form-container {
    
    .form-item {
      padding: 0;
      margin-bottom: 24px;
      
      .label {
        font-size: 16px;
        color: #333;
        margin-bottom: 10px;
        display: block;
        font-weight: 500;
        
        .required {
          color: #ff4d4f;
        }
      }
      
      .input-wrapper {
        height: 44px;
        border-bottom: 1px solid #e5e5e5;
        display: flex;
        align-items: center;
        
        &.position-relative {
          position: relative;
        }
        
        // 下拉建议框样式
        .dropdown-suggestions {
          position: absolute;
          top: 100%;
          left: 0;
          right: 0;
          background-color: #fff;
          border: 1px solid #eaeaea;
          border-radius: 8px;
          max-height: 200px;
          overflow-y: auto;
          z-index: 10;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          margin-top: 5px;
          padding: 5px 0;
          
          .suggestion-item {
            padding: 12px 15px;
            font-size: 15px;
            color: #333;
            
            &:not(:last-child) {
              border-bottom: 1px solid #f5f5f5;
            }
            
            &:active {
              background-color: #f0f9f0;
            }
          }
        }
        
        .input-text {
          flex: 1;
          font-size: 16px;
          color: #333;
          
          &.placeholder {
            color: #999;
          }
        }
        
        .arrow {
          font-size: 20px;
          color: #ccc;
          transform: rotate(90deg);
        }
      }
      
      .salary-input {
        .salary-type-switch {
          display: flex;
          margin-top: 12px;
          
          .salary-type {
            flex: 1;
            height: 36px;
            line-height: 36px;
            text-align: center;
            font-size: 14px;
            color: #666;
            background-color: #f5f5f5;
            
            &:first-child {
              border-radius: 6px 0 0 6px;
            }
            
            &:last-child {
              border-radius: 0 6px 6px 0;
            }
            
            &.active {
              background-color: #5ac725;
              color: #fff;
            }
          }
        }
      }
      
      .location-wrapper {
        display: flex;
        flex-wrap: wrap;
        
        .location-tag {
          height: 36px;
          padding: 0 12px;
          background-color: #f5f5f5;
          border-radius: 18px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 10px;
          margin-bottom: 10px;
          font-size: 14px;
          color: #666;
          
          .remove-icon {
            margin-left: 5px;
            font-size: 16px;
          }
          
          &.add-location {
            border: 1px dashed #ccc;
            background-color: transparent;
            
            .add-icon {
              margin-right: 3px;
            }
          }
        }
      }
      
      .job-type-options {
        display: flex;
        flex-wrap: wrap;
        
        .job-type-option {
          padding: 0 16px;
          height: 36px;
          line-height: 36px;
          border-radius: 18px;
          font-size: 14px;
          color: #666;
          background-color: #f5f5f5;
          margin-right: 10px;
          margin-bottom: 10px;
          
          &.active {
            background-color: #5ac725;
            color: #fff;
          }
        }
      }
    }
  }
  
  .action-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 70px;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 20px;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
    z-index: 9;
    .save-btn {
      width: 100%;
      height: 44px;
      line-height: 44px;
      background-color: #5ac725;
      color: #FFFFFF;
      font-size: 16px;
      font-weight: 500;
      border-radius: 22px;
    }
  }
  
  .picker-popup {
    background-color: #fff;
    border-radius: 12px 12px 0 0;
    overflow: hidden;
    
    .picker-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px 16px;
      border-bottom: 1px solid #f0f0f0;
      
      .title {
        font-size: 16px;
        color: #333;
      }
      
      .cancel-btn {
        font-size: 15px;
        color: #999;
      }
      
      .confirm-btn {
        font-size: 15px;
        color: #5ac725;
      }
    }
    
    .picker-view {
      width: 100%;
      height: 240px;
      
      .picker-item {
        line-height: 36px;
        text-align: center;
        font-size: 16px;
      }
    }
  }
}
</style> 